<template>
    <div class="mt-4">
        <n-drawer v-model:show="rlsdrawer" :width="1200">
            <n-drawer-content title="下发人员" closable>
            <n-card :bordered="false" class="mt-4 proCard">
            <!--表单部分,可以动态创建表单-->
            <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
                <template #statusSlot="{ model, field }">
                    <n-input v-model:value="model[field]" />
                </template>
            </BasicForm>
            <BasicTable
                :columns="columns"
                :request="loadDataTable"
                :row-key="(row:ListData) => row.userId"
                ref="actionRef"
                @update:checked-row-keys="onCheckedRow"
            >
                <template #tableTitle>
                <n-button type="primary" :disabled="isRowKeysEmpty1" @click="releaseequips">
                    下发至设备
                </n-button>
                </template>
                <template #toolbar>
                <n-button type="primary" @click="reloadTable1">刷新数据</n-button>
                </template>
            </BasicTable>
            </n-card>
            </n-drawer-content>
        </n-drawer>
    </div>
  </template>
  <script lang="ts" setup>
  import { ref,defineProps,onMounted,computed, onUnmounted } from 'vue';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { BasicTable } from '@/components/Table';
  import { columns, ListData } from '@/views/equipment/components/rlsempcolumns';
  import { getGroupOptions, getProjcetOptions } from '@/api/employee/employee';
  import { getRlsEmpList,sendToEquip } from '@/api/equipment/equipment_list';
  
  const actionRef = ref();
  const rlsdrawer = ref();

  const props = defineProps(['parentData','show']);
  console.log('**** props:',props.parentData);
  console.log('**** props show:',props.show);
  let tmpequipid = '';
  props.parentData.forEach(item => {
    tmpequipid += item + ',';
    });
  console.log('**** props parentData tmpequipid:',tmpequipid);
  rlsdrawer.value = props.show;

  // 加载数据表
  const intervalId = ref();
  const loadDataTable =  async (res) => {
    const data = await getRlsEmpList({ ...getFieldsValue(), ...res, equipid: tmpequipid });
    return data;
  };

  const rowKeys = ref([]);

  function onCheckedRow(rKeys) {
    console.log('选中的行数据', rKeys);
    rowKeys.value = rKeys;
    console.log('rowKeys.value', rowKeys.value.length);

  }
  
  const isRowKeysEmpty1 = computed(() => {
    return rowKeys.value.length === 0;
  });

  function reloadTable1() {
    if (actionRef) {
      actionRef.value.reload();
    }
  }

  const selectProjectOptions = ref([]);
  const selectGroupOptions = ref([]);
  const isSelectGroupDisabled = ref(true);
  // 获取第一个下拉框的选项数据
  onMounted(async() => {
    try {
      const options = await getProjcetOptions({});
      selectProjectOptions.value = options;
      intervalId.value = setInterval(() => {
        reloadTable1();
      }, 30000);
    } catch (error) {
      console.error('Failed to fetch project options:', error);
    }
  });

  onUnmounted(() => {
      if (intervalId.value) {
        clearInterval(intervalId.value);
      }
  });

  // 获取第二个下拉框的选项数据
  async function fetchAndSetGroupOptions(params) {
    try {
      const options = await getGroupOptions(params);

      selectGroupOptions.value = options;
    } catch (error) {
      console.error('Failed to fetch group options:', error);
    }
  }

  const schemas: FormSchema[] = [
    {
      field: 'selectProject',
      component: 'NSelect',
      label: '选择项目',
      componentProps: {
        clearable: false,
        placeholder: '请选择项目',
        options: selectProjectOptions,
        onUpdateValue: (e: any) => {
          console.log('selectProjectOptions', e);
          if (e === null) {
            // 如果第一个下拉框没有选项，则禁用第二个下拉框
            isSelectGroupDisabled.value = true;
          } else {
            // 否则启用第二个下拉框，并根据需要更新选项
            isSelectGroupDisabled.value = false;
            fetchAndSetGroupOptions({ selectProject: e });
          }
        },
      },
    },
    {
      field: 'selectGroup',
      component: 'NSelect',
      label: '选择班组',
      componentProps: {
        clearable: true,
        disabled: isSelectGroupDisabled,
        placeholder: '请选择班组',
        options: selectGroupOptions,
        onUpdateValue: (e: any) => {
          // console.log('selectGroupOptions', e);
        },
      },
    },
    {
      field: 'searchValue',
      component: 'NInput',
      label: '快速查询',
      componentProps: {
        placeholder: '请输入姓名',
        onInput: (e: any) => {
          // console.log('searchValue', e);
        },
      },
      rules: [{ required: false, message: '请输入姓名', trigger: ['blur'] }],
    },
  ];
  const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '3 s:3 m:4 l:5 xl:6 2xl:7' },
    labelWidth: 90,
    schemas,
    showAdvancedButton: false,
  });

  async function releaseequips() {
    await sendToEquip({equipid: tmpequipid,empList: rowKeys.value}).then((value) => {
      reloadTable1();
    });
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    reloadTable1();
  }

  function handleReset(values: Recordable) {

  }


  </script>
  